import tools from '@/utils/tools.js'
import Icon from '@/components/Icon.vue'
import styles from '@/styles/other/showMessage.module.less'
/**
 * 弹出消息
 * @param {String} content 消息内容
 * @param {String} type 消息类型：info error success warn
 * @param {HTMLElement} container 容器消息会显示到正中心，如果不传则显示到页面中间
 * @param {Number} duration 多久消失ms
 * @param {Function} missingCallback 消失后的回调
 */
export default function (options = {}) {
	const content = options.content || ''
	const type = options.type || 'info'
	const duration = options.duration || 3000
	const container = options.container || document.body
	const missingCallback = options.missingCallback || undefined
	// 创建消息的div
	const div = document.createElement('div')
	const icon = tools.getComponentRootDom(Icon, { type })
	if (getComputedStyle(container, null).position === 'static') {
		container.style.position = 'relative'
	}
	// div里面有span放i元素，div里面放content
	div.innerHTML = `<span class='${styles.icon}'>${icon.outerHTML}</span><div>${content}</div>`
	div.classList.add(styles.message)
	// 根据type渲染background-color
	div.classList.add(styles['message-' + type])
	// 先放入容器里面
	container.appendChild(div)
	// 设置transition
	div.clientHeight
	div.style.opacity = 1
	div.style.transform = 'translate(-50%, -50%)'
	// 设置消失，并触发
	let timer = setTimeout(() => {
		// 这里设置过渡
		div.clientHeight
		div.style.opacity = 0
		div.style.transform = `translate(-50%, -50%) translateY(50px)`
		div.addEventListener(
			'transitionend',
			() => {
				div.remove()
				// 回调方法
				missingCallback && missingCallback()
			},
			{ once: true }
		)
	}, duration)
}
